<template>
  <div class="drug-list">
    <div class="category-filter">
      <button 
        v-for="category in categories" 
        :key="category"
        :class="['category-btn', { active: currentCategory === category }]"
        @click="currentCategory = category"
      >
        {{ category }}
      </button>
    </div>

    <div class="drugs-grid">
      <div v-for="drug in filteredDrugs" :key="drug.id" class="drug-card">
        <img :src="drug.image" :alt="drug.name" class="drug-image">
        <div class="drug-info">
          <h3>{{ drug.name }}</h3>
          <p class="description">{{ drug.description }}</p>
          <p class="price">¥{{ drug.price }}</p>
          <p class="stock">库存: {{ drug.stock }}</p>
          <div class="actions">
            <button 
              class="buy-btn" 
              @click="handleBuy(drug)"
              :disabled="drug.stock <= 0"
            >
              立即购买
            </button>
            <button 
              class="cart-btn" 
              @click="handleAddToCart(drug)"
              :disabled="drug.stock <= 0"
            >
              加入购物车
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 购买确认对话框 -->
    <div v-if="showBuyDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>确认购买</h3>
        <p>商品：{{ selectedDrug?.name }}</p>
        <p>价格：¥{{ selectedDrug?.price }}</p>
        <div class="quantity-selector">
          <button @click="decreaseQuantity">-</button>
          <span>{{ quantity }}</span>
          <button @click="increaseQuantity">+</button>
        </div>
        <div class="dialog-actions">
          <button @click="confirmBuy" class="confirm-btn">确认</button>
          <button @click="cancelBuy" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { API_ENDPOINTS } from '../api/config';
import axios from 'axios';

export default {
  name: 'DrugList',
  data() {
    return {
      drugs: [],
      categories: ['全部', '处方药', '非处方药', '保健品', '医疗器械'],
      currentCategory: '全部',
      showBuyDialog: false,
      selectedDrug: null,
      quantity: 1
    };
  },
  computed: {
    filteredDrugs() {
      if (this.currentCategory === '全部') {
        return this.drugs;
      }
      return this.drugs.filter(drug => drug.category === this.currentCategory);
    }
  },
  methods: {
    async fetchDrugs() {
      try {
        console.log('正在获取用户端药品列表...');
        const response = await axios.get(API_ENDPOINTS.DRUG.GET_ALL);
        console.log('用户端药品列表响应数据:', response.data);
        this.drugs = response.data.map(drug => ({
          ...drug,
          // 确保图片路径是完整的URL，如果不是，则加上后端地址
          image: drug.image ? (drug.image.startsWith('http') ? drug.image : `http://localhost:3000${drug.image}`) : null
        }));
      } catch (error) {
        console.error('获取药品列表失败:', error);
      }
    },
    handleBuy(drug) {
      this.selectedDrug = drug;
      this.quantity = 1;
      this.showBuyDialog = true;
    },
    async handleAddToCart(drug) {
      const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
      if (!userInfo.id) {
        alert('请先登录');
        this.$router.push('/');
        return;
      }

      try {
        // 检查库存
        if (drug.stock <= 0) {
          alert('商品库存不足');
          return;
        }

        const response = await axios.post(API_ENDPOINTS.CART.ADD, {
          drugId: drug.id,
          quantity: 1
        });

        if (response.data && response.data.success) {
          alert('已添加到购物车');
          // 更新购物车数量
          this.$parent.fetchCartCount();
          // 刷新药品列表以更新库存
          this.fetchDrugs();
        } else {
          alert(response.data?.message || '添加到购物车失败');
        }
      } catch (error) {
        console.error('添加到购物车失败:', error);
        if (error.response?.data?.message) {
          alert(error.response.data.message);
        } else {
          alert('添加到购物车失败，请重试');
        }
      }
    },
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },
    increaseQuantity() {
      if (this.quantity < this.selectedDrug.stock) {
        this.quantity++;
      }
    },
    async confirmBuy() {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
        if (!userInfo.id) {
          alert('请先登录');
          this.$router.push('/');
          return;
        }

        // 检查库存
        if (this.quantity > this.selectedDrug.stock) {
          alert('购买数量超过库存');
          return;
        }

        // 创建订单
        const orderResponse = await axios.post(API_ENDPOINTS.ORDER.CREATE, {
          drugId: this.selectedDrug.id,
          quantity: this.quantity
        });

        if (orderResponse.data && orderResponse.data.id) {
          alert('购买成功');
          this.showBuyDialog = false;
          this.fetchDrugs(); // 刷新药品列表
          // 跳转到订单列表
          this.$router.push('/dashboard/orders');
        } else {
          throw new Error('订单创建失败');
        }
      } catch (error) {
        console.error('购买失败:', error);
        if (error.response && error.response.data && error.response.data.message) {
          alert(error.response.data.message);
        } else {
          alert('购买失败，请重试');
        }
      }
    },
    cancelBuy() {
      this.showBuyDialog = false;
      this.selectedDrug = null;
      this.quantity = 1;
    }
  },
  created() {
    this.fetchDrugs();
  }
};
</script>

<style scoped>
.drug-list {
  padding: 20px;
}

.category-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.category-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.category-btn.active {
  background: #42b983;
  color: white;
  border-color: #42b983;
}

.drugs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.drug-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s;
}

.drug-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.drug-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.drug-info {
  padding: 15px;
}

.drug-info h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.description {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 10px;
}

.price {
  color: #e74c3c;
  font-size: 1.2em;
  font-weight: bold;
  margin: 10px 0;
}

.stock {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 15px;
}

.actions {
  display: flex;
  gap: 10px;
}

.buy-btn, .cart-btn {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.buy-btn {
  background-color: #e74c3c;
  color: white;
}

.cart-btn {
  background-color: #42b983;
  color: white;
}

.buy-btn:hover, .cart-btn:hover {
  opacity: 0.9;
}

.buy-btn:disabled, .cart-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 300px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin: 20px 0;
}

.quantity-selector button {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.quantity-selector span {
  min-width: 40px;
  text-align: center;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.confirm-btn, .cancel-btn {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  background-color: #42b983;
  color: white;
}

.cancel-btn {
  background-color: #666;
  color: white;
}
</style>